<?php
namespace app\api\controller\factory;

use think\Controller;
use think\Request;
use app\common\model\user\User as UserModel;
use app\common\model\factory\Factory as FactoryModel;
use think\Db;
use app\common\model\power\Rolepower;
use app\api\controller\Pub;
use app\api\controller\Base;

class Orders extends Base
{
    public function initialize()
    {
        parent::initialize();
        $this->is_login();
        Rolepower::powerguard('301002'); // 工厂订单权限
    }

    private function is_login()
    {
        $data = UserModel::is_sessionlogin();
        if (!$data['code']) {
            $data['options'] = 'relogin';
            json($data)->send();
            exit;
        }
    }
   
    //订单列表
    public function orderList(Request $request)
    {
        $page=$request->get('page') ?? 1;
        $pageSize=$request->get('pageSize') ?? 10;
        $keyword =$request->get('keyword');//物流单号
        $pub=new Pub();
        $user_id=$pub->userid();
        $factory_id = Db::name('user_factory')->where('user_id', $user_id)->value('factory_id');
        if (!$factory_id) {
            return json(['code'=>0, 'msg'=>'未绑定工厂']);
        }
        $query=Db::name('contract_order')
                    ->alias('co')
                    ->join('customer ct','ct.CustomerId=co.customer_id')
                    ->where('factory_id', $factory_id);
        if($keyword){
            $query->where('track_number', 'like', "%$keyword%");
        }
        $orders =   $query
                    ->field('co.id,
                            co.device_id,
                            co.accessories_id,
                            co.track_number,
                            co.status,
                            co.create_time,
                            co.update_time,
                            co.remark,
                            ct.UserName as customer_name,
                            ct.Tel as customer_phone,
                            ct.OtherTel as customer_other_phone,
                            ct.Address as customer_address
                            ')
                    ->paginate([
                        'list_rows' => $pageSize,
                        'page'      => $page,
                    ]);
         $orderList = $orders->toArray()['data'];
    
        // 处理数据
        $processedOrders = [];
        foreach ($orderList as $order) {
            // 获取设备信息
            $deviceIds = explode(',', $order['device_id']);
            $devices = Db::name('device')
                ->whereIn('id', $deviceIds)
                ->field('id,name')
                ->select();
                
            // 获取配件信息
            $accessories = [];
            if (!empty($order['accessories_id'])) {
                $accessoryIds = explode(',', $order['accessories_id']);
                $accessories = Db::name('accessories')
                    ->whereIn('id', $accessoryIds)
                    ->select();
            }
            
            // 格式化时间
            $order['create_time'] = date('Y-m-d H:i:s', $order['create_time']);
            $order['update_time'] = date('Y-m-d H:i:s', $order['update_time']);
            
            // 按设备ID分组配件
            $accessoriesByDevice = [];
            foreach ($accessories as $acc) {
                $accessoriesByDevice[$acc['device_id']][] = $acc;
            }
            
            // 为每个设备添加配件信息
            foreach ($devices as &$dev) {
                $dev['accessories'] = $accessoriesByDevice[$dev['id']] ?? [];
            }
            unset($dev); 
            
            // 构建处理后的订单数据
            $processedOrders[] = [
                'id' => $order['id'],
                'track_number' => $order['track_number'],
                'status' => $order['status'],
                'create_time' => $order['create_time'],
                'update_time' => $order['update_time'],
                'device' => $devices,
                'remark' => $order['remark'],
                'customer_name' =>$order['customer_name'],
                'customer_phone' =>$order['customer_phone'],
                'customer_address' =>$order['customer_address'],
                'customer_other_phone' =>$order['customer_other_phone'],
                
            ];
        }

        $result = $orders->toArray();
        $result['data'] = $processedOrders;
        
        return json(['code' => 1, 'msg' => 'success', 'data' => $result]);
    }

    public function orderStatusChange(Request $request)
    {
        $data = $request->post();
        if (empty($data['id']) || empty($data['track_number']) || empty($data['status'])) {
            return json(['code'=>0, 'msg'=>'参数不完整']);
        }
        $order = Db::name('contract_order')->where('id', $data['id'])->find();
        if (!$order) {
            return json(['code'=>0, 'msg'=>'订单不存在']);
        }
        Db::name('contract_order')->where('id', $data['id'])->update([
            'track_number' => $data['track_number'],
            'status' => $data['status'],
            'update_time' => time()
        ]);
        return json(['code'=>1, 'msg'=>'修改成功']);
    }
} 